package com.probox.common.entity.service.customer.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.probox.common.core.enums.CustomerFundBizTypeEnum;
import com.probox.common.core.enums.CustomerFundHistoryTypeEnum;
import com.probox.common.core.enums.DataStatus;
import com.probox.common.core.enums.OrderRechargeEnum;
import com.probox.common.core.utils.SecurityUtils;
import com.probox.common.core.utils.StringUtils;
import com.probox.common.entity.vo.CustomerFundVo;
import com.probox.customer.api.domain.CustomerFundDetailVo;
import com.probox.customer.api.domain.CustomerInfoAccount;
import com.probox.common.entity.domain.customer.CustomerFund;
import com.probox.common.entity.domain.customer.CustomerFundDetail;
import com.probox.common.entity.domain.customer.CustomerInfo;
import com.probox.common.entity.mapper.customer.CustomerFundDetailMapper;
import com.probox.common.entity.mapper.customer.CustomerFundMapper;
import com.probox.common.entity.mapper.customer.CustomerInfoAccountMapper;
import com.probox.common.entity.mapper.customer.CustomerInfoMapper;
import com.probox.common.entity.service.customer.ICustomerFundDetailService;
import com.probox.common.entity.vo.customer.open.CustomerFundBillOpenVo;
import com.probox.order.api.domain.OrderQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 客户资金明细Service业务层处理
 *
 * @author zsy
 * @date 2021-06-18
 */
@Service
@Transactional
public class CustomerFundDetailServiceImpl extends ServiceImpl<CustomerFundDetailMapper, CustomerFundDetail> implements ICustomerFundDetailService {
    @Autowired
    private CustomerFundDetailMapper customerFundDetailMapper;

    @Autowired
    private CustomerFundMapper customerFundMapper;

    @Autowired
    private CustomerInfoMapper customerInfoMapper;

    @Autowired
    private CustomerInfoAccountMapper customerInfoAccountMapper;

    /**
     * 查询客户资金明细
     *
     * @param detailUid 客户资金明细ID
     * @return 客户资金明细
     */
    @Override
    public CustomerFundDetail selectCustomerFundDetailById(Long detailUid) {
        return this.getById(detailUid);
    }

    /**
     * 查询客户资金明细列表
     *
     * @param customerFundDetail 客户资金明细
     * @return 客户资金明细
     */
    @Override
    public List<CustomerFundDetail> queryList(CustomerFundDetail customerFundDetail) {
        QueryWrapper<CustomerFundDetail> queryWrapper = Wrappers.query();
        if (StringUtils.isNotEmpty(customerFundDetail.getBizType())) {
            queryWrapper.eq("BIZ_TYPE", customerFundDetail.getBizType());
        }
        queryWrapper.eq("DATA_STATUS", customerFundDetail.getDataStatus());
        queryWrapper.eq("CUSTOMER_UID",customerFundDetail.getCustomerUid());
        if (StringUtils.isNotEmpty(String.valueOf(customerFundDetail.getBizNo())) && customerFundDetail.getBizNo() != null) {
            queryWrapper.eq("BIZ_NO", customerFundDetail.getBizNo());
        }

        if (StringUtils.isNotEmpty(String.valueOf(customerFundDetail.getBizTime())) && customerFundDetail.getBizTime() != null) {
            queryWrapper.eq("BIZ_TIME", customerFundDetail.getBizTime());
        }
        if (StringUtils.isNotEmpty(customerFundDetail.getFundStatus())){
            queryWrapper.eq("FUND_STATUS", customerFundDetail.getFundStatus());
        }
        if (customerFundDetail.getOrderUid() != null){
            queryWrapper.eq("order_uid", customerFundDetail.getOrderUid());
        }
        if (customerFundDetail.getItemUid() != null){
            queryWrapper.eq("item_uid", customerFundDetail.getItemUid());
        }
        queryWrapper.ne("AMOUNT",0);
        queryWrapper.orderByDesc("CREATE_TIME");
        return customerFundDetailMapper.selectList(queryWrapper);
    }

    @Override
    public List<CustomerFundDetail> queryWaitDeductList() {
        QueryWrapper<CustomerFundDetail> queryWrapper = Wrappers.query();
        queryWrapper.eq("DATA_STATUS", "0");
        queryWrapper.last(" and DATE_ADD(CREATE_TIME,INTERVAL expire_hour HOUR)<SYSDATE() order by CREATE_TIME asc limit 10 ");
        return customerFundDetailMapper.selectList(queryWrapper);
    }

    @Override
    public List<CustomerFundDetailVo> queryDeductList(CustomerFundDetail customerFundDetail) {
        return customerFundDetailMapper.queryDeductList(customerFundDetail);
    }

    /**
     * 新增客户资金明细
     *
     * @param customerFundDetail 客户资金明细
     * @return 结果
     */
    @Override
    public boolean insertCustomerFundDetail(CustomerFundDetail customerFundDetail) {

        return this.save(customerFundDetail);

    }

    /**
     * 修改客户资金明细
     *
     * @param customerFundDetail 客户资金明细
     * @return 结果
     */
    @Override
    public boolean updateCustomerFundDetail(CustomerFundDetail customerFundDetail) {

        return this.updateById(customerFundDetail);
    }

    /**
     * 批量删除客户资金明细
     *
     * @param detailUids 需要删除的客户资金明细ID
     * @return 结果
     */
    @Override
    public boolean deleteCustomerFundDetailByIds(Long[] detailUids) {
        return this.removeByIds(Arrays.asList(detailUids));
    }

    @Override
    public List<CustomerFundDetail> getFundDetail(Long customerId) {
        return customerFundDetailMapper.getFundDetail(customerId);
    }

    @Override
    public List<CustomerFundDetail> selectCustomerAllProfit(Long customerUid) {
        QueryWrapper<CustomerFundDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("BIZ_TYPE", CustomerFundBizTypeEnum.profit.getKey());
        queryWrapper.eq("DATA_STATUS", DataStatus.valid.getKey());
        queryWrapper.eq("CUSTOMER_UID",customerUid);

        List<CustomerFundDetail> customerFundDetails = customerFundDetailMapper.selectList(queryWrapper);
        return customerFundDetails;
    }

    @Override
    public List<CustomerFundDetail> selectMyFundDetail(CustomerFundDetail customerFundDetail) {
        QueryWrapper<CustomerFundDetail> queryWrapper = Wrappers.query();
        queryWrapper.eq("BIZ_TYPE", customerFundDetail.getBizType());
        if (customerFundDetail != null){
            queryWrapper.eq("DATA_STATUS", customerFundDetail.getDataStatus());
        }
        if (StringUtils.isNotEmpty(customerFundDetail.getBizDesc())){
            queryWrapper.eq("biz_desc", customerFundDetail.getBizDesc());
        }
        if (StringUtils.isNotEmpty(customerFundDetail.getFundStatus())){
            queryWrapper.eq("fund_status", customerFundDetail.getFundStatus());
        }
        if (StringUtils.isNotEmpty(customerFundDetail.getStartDate())){
            queryWrapper.ge("BIZ_TIME", customerFundDetail.getStartDate());
            queryWrapper.le("BIZ_TIME", customerFundDetail.getEndDate());
        }
        queryWrapper.eq("CUSTOMER_UID", SecurityUtils.getCustomerUid());
        //queryWrapper.ne("AMOUNT",0);
        queryWrapper.orderByDesc("CREATE_TIME");
        return customerFundDetailMapper.selectList(queryWrapper);
    }

    @Override
    public List<CustomerFundDetail> selectDeduct(CustomerFundVo vo) {
        QueryWrapper<CustomerFundDetail> queryWrapper = Wrappers.query();
        List<String> bizDesc = new ArrayList<>();
        bizDesc.add("抵扣积分");
        bizDesc.add("抵扣排版");
        if (StringUtils.isNotEmpty(vo.getDeductType())){
            queryWrapper.eq("DEDUCT_TYPE", vo.getDeductType());
        }else{
            queryWrapper.in("DEDUCT_TYPE", bizDesc);
        }

        if (StringUtils.isNotEmpty(vo.getStartDate())){
            queryWrapper.ge("BIZ_TIME", vo.getStartDate());
            queryWrapper.le("BIZ_TIME", vo.getEndDate());
        }
        queryWrapper.eq("CUSTOMER_UID", SecurityUtils.getCustomerUid());
        //queryWrapper.ne("AMOUNT",0);
        queryWrapper.orderByDesc("CREATE_TIME");
        return customerFundDetailMapper.selectList(queryWrapper);
    }

    @Override
    public Integer selectDeductCount(CustomerFundVo vo) {
        QueryWrapper<CustomerFundDetail> queryWrapper = Wrappers.query();
        List<String> bizDesc = new ArrayList<>();
        bizDesc.add("抵扣积分");
        bizDesc.add("抵扣排版");
        if (StringUtils.isNotEmpty(vo.getDeductType())){
            queryWrapper.eq("DEDUCT_TYPE", vo.getDeductType());
        }else{
            queryWrapper.in("DEDUCT_TYPE", bizDesc);
        }

        if (StringUtils.isNotEmpty(vo.getStartDate())){
            queryWrapper.ge("BIZ_TIME", vo.getStartDate());
            queryWrapper.le("BIZ_TIME", vo.getEndDate());
        }
        queryWrapper.eq("CUSTOMER_UID", SecurityUtils.getCustomerUid());

        return customerFundDetailMapper.selectCount(queryWrapper);
    }

    @Override
    public Integer selectMyFundDetailCount(CustomerFundDetail customerFundDetail) {
        QueryWrapper<CustomerFundDetail> queryWrapper = Wrappers.query();
        queryWrapper.eq("BIZ_TYPE", customerFundDetail.getBizType());
        if (customerFundDetail != null){
            queryWrapper.eq("DATA_STATUS", customerFundDetail.getDataStatus());
        }
        queryWrapper.eq("CUSTOMER_UID", SecurityUtils.getCustomerUid());
        if (StringUtils.isNotEmpty(customerFundDetail.getBizDesc())){
            queryWrapper.eq("biz_desc", customerFundDetail.getBizDesc());
        }
        if (StringUtils.isNotEmpty(customerFundDetail.getFundStatus())){
            queryWrapper.eq("fund_status", customerFundDetail.getFundStatus());
        }
        if (StringUtils.isNotEmpty(customerFundDetail.getStartDate())){
            queryWrapper.ge("BIZ_TIME", customerFundDetail.getStartDate());
            queryWrapper.le("BIZ_TIME", customerFundDetail.getEndDate());
        }
        return customerFundDetailMapper.selectCount(queryWrapper);
    }

    @Override
    public List<CustomerFundBillOpenVo> getFundBill() {
        List<CustomerFundBillOpenVo> fundBillOpenVoList = new ArrayList<>();
        QueryWrapper<CustomerFundDetail> fundDetailQueryWrapper = new QueryWrapper<>();
        fundDetailQueryWrapper.eq("CUSTOMER_UID",SecurityUtils.getCustomerUid());
        fundDetailQueryWrapper.eq("BIZ_TYPE",CustomerFundBizTypeEnum.balance.getKey());
        fundDetailQueryWrapper.eq("DATA_STATUS",DataStatus.valid.getKey());
        fundDetailQueryWrapper.orderByDesc("CREATE_TIME");
        List<CustomerFundDetail> customerFundDetails = customerFundDetailMapper.selectList(fundDetailQueryWrapper);
        for (CustomerFundDetail fundDetail:customerFundDetails){
            CustomerFundBillOpenVo fundBillOpenVo = new CustomerFundBillOpenVo();
            fundBillOpenVo.setFundDesc(fundDetail.getRemark());
            fundBillOpenVo.setFundTime(fundDetail.getCreateTime());
            if (fundDetail.getAmount() < 0 ){
                fundBillOpenVo.setFundAmont(fundDetail.getAmountStr());
                fundBillOpenVo.setFundStatus(CustomerFundHistoryTypeEnum.outflow.getKey());
            }else {
                if(!StringUtils.isEmpty(fundDetail.getAmountStr())){
                    fundBillOpenVo.setFundAmont("+"+fundDetail.getAmountStr());
                }else{
                    fundBillOpenVo.setFundAmont("+"+0);
                }
                if (!OrderRechargeEnum.recharge.getValue().equals(fundDetail.getRemark())){
                    //余额退款
                    fundBillOpenVo.setFundStatus(CustomerFundHistoryTypeEnum.flowInto.getKey());
                }else {
                    //充值余额
                    fundBillOpenVo.setFundStatus(CustomerFundHistoryTypeEnum.flowInto.getKey());
                }
            }
            fundBillOpenVoList.add(fundBillOpenVo);
        }
        return fundBillOpenVoList;
    }

    /**
     * 总收益详细
     * @param customerFundDetail
     * @return
     */
    @Override
    public List<CustomerFundDetail> getAllProfitDetail(CustomerFundDetail customerFundDetail) {
        QueryWrapper<CustomerFundDetail> queryWrapper = Wrappers.query();
        queryWrapper.eq("BIZ_TYPE", customerFundDetail.getBizType());
        queryWrapper.eq("CUSTOMER_UID", SecurityUtils.getCustomerUid());
        queryWrapper.orderByDesc("CREATE_TIME");
        return customerFundDetailMapper.selectList(queryWrapper);
    }


    /**
     * 总收益详细条数
     * @param customerFundDetail
     * @return
     */
    @Override
    public Integer getAllProfitDetailCount(CustomerFundDetail customerFundDetail) {
        QueryWrapper<CustomerFundDetail> queryWrapper = Wrappers.query();
        queryWrapper.eq("BIZ_TYPE", customerFundDetail.getBizType());
        if (customerFundDetail != null){
            queryWrapper.eq("DATA_STATUS", customerFundDetail.getDataStatus());
        }
        queryWrapper.eq("CUSTOMER_UID", SecurityUtils.getCustomerUid());
        return customerFundDetailMapper.selectCount(queryWrapper);
    }

    /**
     * 我的-账单总条数
     * @return
     */
    @Override
    public Integer getFundBillCount() {
        List<CustomerFundBillOpenVo> fundBillOpenVoList = new ArrayList<>();
        QueryWrapper<CustomerFundDetail> fundDetailQueryWrapper = new QueryWrapper<>();
        fundDetailQueryWrapper.eq("CUSTOMER_UID",SecurityUtils.getCustomerUid());
        fundDetailQueryWrapper.eq("BIZ_TYPE",CustomerFundBizTypeEnum.balance.getKey());
        fundDetailQueryWrapper.eq("DATA_STATUS",DataStatus.valid.getKey());
        fundDetailQueryWrapper.orderByDesc("CREATE_TIME");
        Integer count = customerFundDetailMapper.selectCount(fundDetailQueryWrapper);
        return count;
    }

    @Override
    public List<CustomerInfo> getFreeCustomerInfo(Long customerUid,String fansStatus) {
        //查询有多少父级id等于当前客户
        QueryWrapper<CustomerInfo> infoQueryWrapper = new QueryWrapper<>();
        infoQueryWrapper.eq("STATUS",DataStatus.valid.getKey());
        infoQueryWrapper.eq("PLATFORM_UID",SecurityUtils.getPlatformId());
        if ("1".equals(fansStatus)){
            infoQueryWrapper.eq("FATHER_UID",customerUid);
        }
        if ("2".equals(fansStatus)){
            infoQueryWrapper.eq("GRAND_FATHER_UID",customerUid);
        }
        List<CustomerInfo> customerInfoList = customerInfoMapper.selectList(infoQueryWrapper);
        return customerInfoList;
    }

    /**
     * 统计订单用户冻结分润资金明细
     * @param orderNo
     * @return
     */
    public List<CustomerFundDetailVo> getOrderFreezeProfit(List<String> orderNo){
        List<CustomerFundDetailVo> voList = null;
        for (String bizNo:orderNo){
            voList = customerFundDetailMapper.getOrderFreezeProfit(bizNo);
            if(ObjectUtil.isNotEmpty(voList)){
                QueryWrapper<CustomerInfoAccount> queryWrapper = null;
                List<CustomerInfoAccount> customerInfoAccountList = null;
                for(CustomerFundDetailVo vo:voList){
                    queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("CUSTOMER_UID",vo.getCustomerUid());
                    customerInfoAccountList = customerInfoAccountMapper.selectList(queryWrapper);
                    if(ObjectUtil.isNotEmpty(customerInfoAccountList)){
                        for (CustomerInfoAccount account:customerInfoAccountList){
                            if (account.getOpenId()!=null){
                                vo.setOpenId(account.getOpenId());
                            }
                        }
                    }
                }
            }
        }
        return voList;
    }

    /**
     * 订单下分润冻结的资金明细解冻
     * @param orderNo
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    @Override
    public Boolean setValidOrderProfit(List<String> orderNo) {
        boolean update = false;
        for (String no:orderNo){
            //修改资金
            List<CustomerFundDetail> customerFundDetailList = customerFundDetailMapper.selectAmountAndCustomer(no);
            for (CustomerFundDetail fundDetail:customerFundDetailList){
                CustomerFund fund = new CustomerFund();
                fund.setCustomerUid(fundDetail.getCustomerUid());
                fund.setProfit(fundDetail.getAmount());
                customerFundMapper.unfreezeCustomerFund(fund);
            }
            //解冻客户资金
            LambdaUpdateChainWrapper<CustomerFundDetail> lambdaUpdateChainWrapper = new LambdaUpdateChainWrapper<CustomerFundDetail>(customerFundDetailMapper);
            update = lambdaUpdateChainWrapper.eq(CustomerFundDetail::getBizNo, no)
                                .eq(CustomerFundDetail::getBizType, CustomerFundBizTypeEnum.profit.getKey())
                                .eq(CustomerFundDetail::getDataStatus,"2")
                                .set(CustomerFundDetail::getDataStatus, DataStatus.valid.getKey()).update();
        }

        return update;
    }


    @Override
    public Long countJiFen(OrderQuery query) {
        return customerFundDetailMapper.countJiFen(query);
    }


}
